import 'package:fig/sqlite/sql_manager.dart';
import 'package:sqflite_common/sqlite_api.dart';

class TableMediaLang extends TableBase {
  // 表名
  final String tableName = 'media_lang';
  static final String columnName = "name";

  Future<void> insertAllWithMediaId(int mediaId, String langs, {Database database}) async {
    if (database == null) {
      database = await SqlManager.getCurrentDatabase();
    }

    if (langs == null || langs == "") {
      return;
    }

    var langList = langs.split(',');
    for (String lang in langList) {
      if (lang == null || lang == "") {
        continue;
      }
      final langId = await install(mediaId, lang, database: database);
      installMap(mediaId, langId, database: database);
    }
  }

  // 保存演员信息
  Future<int> install(int mediaId, String lang, {Database database}) async {
    var existLangList = await database.query(tableName, where: '$columnName=?', whereArgs: [lang]);
    var langId = 0;
    if (existLangList.length == 0) {
      langId = await database.insert(tableName, {
        '$columnName': lang,
        '${TableBase.columnCreateTime}': DateTime.now().millisecondsSinceEpoch,
      });
    } else {
      langId = existLangList[0]['${TableBase.columnId}'];
    }
    return langId;
  }

  // 保存影视关联信息
  Future<void> installMap(int mediaId, int langId, {Database database}) async {
    var existLangMapList = await database.query(
      TableMediaLangMap.tableName,
      where: '${TableMediaLangMap.columnMediaId}=? and ${TableMediaLangMap.columnLangId}=?',
      whereArgs: [mediaId, langId],
    );

    if (existLangMapList.length == 0) {
      database.insert(TableMediaLangMap.tableName, {
        '${TableMediaLangMap.columnMediaId}': mediaId,
        '${TableMediaLangMap.columnLangId}': langId,
        '${TableBase.columnCreateTime}': DateTime.now().millisecondsSinceEpoch,
      });
    }
  }

  @override
  createTable(Database db) {
    db.execute('''create table $tableName (
    ${TableBase.columnId} integer PRIMARY KEY AUTOINCREMENT NOT NULL,
    $columnName text,
    ${TableBase.columnCreateTime} integer
    )''');
  }
}

class TableMediaLangMap extends TableBase {
  // 表名
  static final String tableName = 'media_lang_map';
  static final String columnLangId = "lang_id";
  static final String columnMediaId = "media_id";

  @override
  createTable(Database db) {
    db.execute('''create table $tableName (
    ${TableBase.columnId} integer PRIMARY KEY AUTOINCREMENT NOT NULL,
    $columnLangId integer,
    $columnMediaId integer,
    ${TableBase.columnCreateTime} integer
    )''');
  }
}
